//
//  AddPingLunCon.m
//  ShopDemo
//
//  Created by 飞扬的青春 on 2018/8/4.
//  Copyright © 2018年 飞扬的青春. All rights reserved.
//

#import "AddPingLunCon.h"
#import "MMTextAttachment.h"
#import "AFNetworking.h"
@interface AddPingLunCon ()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property(nonatomic,strong)UITextView *editTV;
@property(nonatomic,strong)UIView *chooseview;
@property(nonatomic,strong)UIButton *choosebtn;

@property(nonatomic,strong)NSMutableArray *imageArray;
@property(nonatomic,strong)UIImage *titimage;
@property(nonatomic,strong)NSString *titimageType;
@property(nonatomic,strong)UIImageView *titimagevi;
@property(nonatomic,strong)UITextField *bittifield;
@end

@implementation AddPingLunCon
{
    NSMutableArray *_imgArr;
    NSMutableAttributedString *_string;
}

-(NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _imageArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.titimageType = @"";
    _imgArr = [NSMutableArray new];
    self.view.backgroundColor = LineBackColor;
    [self creatHeaderMethod];
    [self creatchooseviewMethod];
}

-(void)creatchooseviewMethod{
    self.chooseview = [UIView new];
    self.chooseview.backgroundColor = LineBackColor;
    [self.view addSubview:self.chooseview];
    self.chooseview.sd_layout
    .topSpaceToView(self.view, 113*kJLXWidthScale)
    .leftSpaceToView(self.view, 120*kJLXWidthScale)
    .rightSpaceToView(self.view, 50*kJLXWidthScale)
    .heightIs(self.dataArray.count*50*kJLXWidthScale);
    for (int i = 0; i < self.dataArray.count; i ++) {
        NSDictionary *dic = self.dataArray[i];
        MineButton *btn = [MineButton buttonWithType:UIButtonTypeSystem];
        btn.usinfo = dic;
        [btn setTitle:dic[@"SORT_NAME"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(chooselinButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.chooseview addSubview:btn];
        btn.sd_layout
        .topSpaceToView(self.chooseview, 50*kJLXWidthScale*i)
        .leftSpaceToView(self.chooseview, 0)
        .rightSpaceToView(self.chooseview, 0)
        .heightIs(50*kJLXWidthScale);
    }
    self.chooseview.hidden = YES;
}

-(void)chooselinButtonAction:(MineButton *)sender{
    [self.choosebtn setTitle:sender.usinfo[@"SORT_NAME"] forState:UIControlStateNormal];
    self.chooseview.hidden = YES;
}

-(void)creatHeaderMethod{
    for (int i = 0; i < 3; i ++) {
        UIView *backview = [UIView new];
        backview.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:backview];
        backview.sd_layout
        .topSpaceToView(self.view, 8*kJLXWidthScale + i*50*kJLXWidthScale + i*5*kJLXWidthScale)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .heightIs(50*kJLXWidthScale);
        
        UILabel *lab = [UILabel new];
        lab.font = [UIFont systemFontOfSize:17*kJLXWidthScale];
        lab.textColor = [UIColor orangeColor];
        [backview addSubview:lab];
        if (i == 0) {
            lab.text = @"标题：";
            lab.sd_layout
            .topSpaceToView(backview, 0)
            .bottomSpaceToView(backview, 0)
            .leftSpaceToView(backview, 15*kJLXWidthScale)
            .widthIs(60*kJLXWidthScale);
            UITextField *field = [UITextField new];
            field.placeholder = @"标题";
            self.bittifield = field;
            field.font = [UIFont systemFontOfSize:17*kJLXWidthScale];
            [backview addSubview:field];
            field.sd_layout
            .topSpaceToView(backview, 0)
            .leftSpaceToView(lab, 0)
            .bottomSpaceToView(backview, 0)
            .rightSpaceToView(backview, 10*kJLXWidthScale);
        }else if(i == 1){
            lab.text = @"选择分类：";
            lab.sd_layout
            .topSpaceToView(backview, 0)
            .bottomSpaceToView(backview, 0)
            .leftSpaceToView(backview, 15*kJLXWidthScale)
            .widthIs(110*kJLXWidthScale);
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
            NSDictionary *dic = self.dataArray[0];
            self.choosebtn = btn;
            [btn setTitle:dic[@"SORT_NAME"] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(chooseButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            btn.backgroundColor = [UIColor whiteColor];
            [backview addSubview:btn];
            btn.sd_layout
            .topSpaceToView(backview, 0)
            .leftSpaceToView(lab,0)
            .rightSpaceToView(backview, 50*kJLXWidthScale)
            .bottomSpaceToView(backview, 0);
            
        }else{
            lab.text = @"封面图片：";
            lab.sd_layout
            .topSpaceToView(backview, 0)
            .bottomSpaceToView(backview, 0)
            .leftSpaceToView(backview, 15*kJLXWidthScale)
            .widthIs(100*kJLXWidthScale);
            
            UIImageView *titimage = [UIImageView new];
            self.titimagevi = titimage;
            titimage.backgroundColor = [UIColor whiteColor];
            [backview addSubview:titimage];
            titimage.sd_layout
            .topSpaceToView(backview, 0)
            .leftSpaceToView(lab,0)
            .rightSpaceToView(backview, 40*kJLXWidthScale)
            .bottomSpaceToView(backview, 0);
            
            titimage.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titImageAction:)];
            [titimage addGestureRecognizer:tap];
            
            
            UIImageView *imagevi = [UIImageView new];
            imagevi.image = [UIImage imageNamed:@"Right.png"];
            [backview addSubview:imagevi];
            imagevi.sd_layout
            .centerYEqualToView(backview)
            .rightSpaceToView(backview,0)
            .heightIs(30*kJLXWidthScale)
            .widthIs(30*kJLXWidthScale);
        }
        
    }
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 5*kJLXWidthScale;
    btn.layer.borderColor = [UIColor orangeColor].CGColor;
    btn.layer.borderWidth = 1;
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitle:@"发布" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(FaBuButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    btn.sd_layout
    .bottomSpaceToView(self.view, 10*kJLXWidthScale)
    .leftSpaceToView(self.view, 20*kJLXWidthScale)
    .rightSpaceToView(self.view, 20*kJLXWidthScale)
    .heightIs(45*kJLXWidthScale);
    if (kScreenHeight == 812) {
        btn.sd_layout
        .bottomSpaceToView(self.view, 34)
        .leftSpaceToView(self.view, 20*kJLXWidthScale)
        .rightSpaceToView(self.view, 20*kJLXWidthScale)
        .heightIs(45*kJLXWidthScale);
    }
    
    UITextView *textview = [UITextView new];
    self.editTV = textview;
    textview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:textview];
    textview.sd_layout
    .topSpaceToView(self.view, 172*kJLXWidthScale)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0)
    .bottomSpaceToView(btn, 20*kJLXWidthScale);
    
    UIButton *adimagbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [adimagbtn setImage:[UIImage imageNamed:@"add_icon.png"] forState:UIControlStateNormal];
    adimagbtn.backgroundColor = [UIColor whiteColor];
    [adimagbtn addTarget:self action:@selector(addimageButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:adimagbtn];
    adimagbtn.sd_layout
    .bottomSpaceToView(btn, 25*kJLXWidthScale)
    .leftSpaceToView(self.view, 8*kJLXWidthScale)
    .heightIs(45*kJLXWidthScale)
    .widthIs(45*kJLXWidthScale);
    
    
    
}

-(void)titImageAction:(UITapGestureRecognizer *)tap{
    self.titimageType = @"100";
    [self.view endEditing:YES];
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }else{
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    
    sheet.tag = 255;
    [sheet showInView:self.view];
    
}
-(void)FaBuButtonAction:(UIButton *)sender{
    
    NSAttributedString * att = self.editTV.attributedText;
    NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];
    //枚举出所有的附件字符串
    [att enumerateAttributesInRange:NSMakeRange(0, att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        NSTextAttachment * textAtt = attrs[@"NSAttachment"];//从字典中取得那一个图片
        if (textAtt){
            //            UIImage * image = textAtt.image;
            [self.imageArray addObject:textAtt.image];
            NSString * text = @"图片位置";
            [resutlAtt replaceCharactersInRange:range withString:text];
        }
    }];
    
    /*
     接口传参    TITLE标题
     SHORTCONTENT  摘要简述
     NAME 文章来源,发文人名称
     CONTENT 内容
     USER_ID 添加人ID
     IMAGE 摘要图片
     FILE1,FILE2,FILE3 内容图片
     否需要分页    否
     接口地址    news/app/save.do
     返回接口    map
     */
    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:@"/dashop/news/app/save.do"];
    NSDictionary *dic = @{@"TITLE":self.bittifield.text,@"SHORTCONTENT":@"test",@"NAME":[UserDefault objectForKey:LogUserName],@"CONTENT":self.editTV.text,@"USER_ID":[UserDefault objectForKey:LogUserID]};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //ContentType设置
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    [manager POST:endstr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩图片像素
        NSData *titdata = UIImagePNGRepresentation(self.titimage);
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:titdata
                                    name:@"IMAGE"
                                fileName:@"iOS.png"
                                mimeType:@"image/png"];
        if (self.imageArray.count > 0) {
            for (int i = 1; i < self.imageArray.count; i ++) {
                NSString *namestr = [NSString stringWithFormat:@"FILE%d",i+1];
                NSData *filedata = UIImagePNGRepresentation(self.imageArray[i]);
                //上传的参数(上传图片，以文件流的格式)
                [formData appendPartWithFileData:filedata
                                            name:namestr
                                        fileName:@"iOS.png"
                                        mimeType:@"image/png"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *jsonstr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [MethodClass dictionaryWithJsonString:jsonstr];
        if ([dic[@"RESULT"] integerValue] == 1) {
            [self alerWithMessage:dic[@"MESSAGE"]];
            self.editTV.text = @"";
            self.imageArray = [NSMutableArray array];
            self.titimage = nil;
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self alerWithMessage:dic[@"MESSAGE"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

//封装提示框方法
-(void)alerWithMessage:(NSString *)msg{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        //延迟1秒自动消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}


-(void)ContentMethod:(NSString *)url{
//    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
//    } successBlock:^(id response) {
//        NSDictionary *dic = response;
//        if ([dic[@"RESULT"] integerValue] == 1 || [dic[@"RESULT"] integerValue] == -1) {
//
//        }
//    } failBlock:^(NSError *error) {
//
//    }];
    
   
    
    
}

-(void)chooseButtonAction:(UIButton *)sender{
    
    self.chooseview.hidden = !self.chooseview.hidden;
    
}


-(void)addimageButtonAction:(UIButton *)sender{
    self.titimageType = @"";
    [self.view endEditing:YES];
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }else{
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    
    sheet.tag = 255;
    [sheet showInView:self.view];
}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        NSUInteger sourceType = 0;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 取消
                    return;
                case 1:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 2:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }else {
            if (buttonIndex == 0) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
    }
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     * UIImagePickerControllerMediaURL;       // an NSURL
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     */
    // 保存图片至本地，方法见下文
//    NSLog(@"img = %@",image);
    image = [self compressImage:image toMaxFileSize:0.2];
    if (self.titimageType.length > 0) {
        self.titimage = image;
        self.titimagevi.image = image;
        return;
    }
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithAttributedString:self.editTV.attributedText];
    MMTextAttachment* textAttachment = [[ MMTextAttachment alloc] initWithData:nil ofType:nil];
    UIImage * smileImage = image;
    textAttachment.image = smileImage ;
    NSAttributedString * textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;
    
    NSAttributedString *nString = [[NSAttributedString alloc] initWithString:@"\n" attributes:nil];
    [string insertAttributedString:nString atIndex:self.editTV.selectedRange.location];
    [string insertAttributedString:textAttachmentString atIndex:self.editTV.selectedRange.location + 1];
    [string insertAttributedString:nString atIndex:self.editTV.selectedRange.location + 2];
    self.editTV.attributedText = string ;
    [self.editTV becomeFirstResponder];
}

- (UIImage *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
}


//把带有图片的属性字符串转成普通的字符串
-(NSString *)textString{
    NSAttributedString * att = self.editTV.attributedText;
    NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];
    //枚举出所有的附件字符串
    [att enumerateAttributesInRange:NSMakeRange(0, att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        NSTextAttachment * textAtt = attrs[@"NSAttachment"];//从字典中取得那一个图片
        if (textAtt){
            //            UIImage * image = textAtt.image;
            NSString * text = @"图片位置";
            [resutlAtt replaceCharactersInRange:range withString:text];
        }
    }];
    return resutlAtt.string;
}
     


@end
